package com.hu.bgp.client.place;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;
import com.hu.bgp.client.EventBus;
import com.hu.bgp.client.localevent.PlaceChangedEvent;
import com.hu.bgp.client.localevent.RequestPlaceChange;
import com.hu.bgp.client.localevent.RequestPlaceChangeHandler;
import com.hu.bgp.client.presenter.BoardgamePlace;
import com.hu.bgp.client.presenter.GameSessionPlace;
import com.hu.bgp.client.presenter.GameTypePlace;
import com.hu.bgp.framework.clientapi.util.Firebug;




public class PlaceService implements ValueChangeHandler<String>
{

	private EventBus eventBus;
	public PlaceService(EventBus eventBus){
		this.eventBus = eventBus;
		bind();
	}
	
	
	private void bind() {
		History.addValueChangeHandler(this);
		
		eventBus.addHandler(RequestPlaceChange.TYPE, new RequestPlaceChangeHandler(){

			public void handlePlaceRequest(Place place) {
				Firebug.debug("RequestPlaceChange: " + place.asURI());
				History.newItem(place.asURI(),true);
				
			}
			
		});
	}
	
	public void onValueChange(ValueChangeEvent<String> event) {
		String token = event.getValue();
		String place = "";
		if(token.indexOf("!") > 0)
			 place = token.substring(0, token.indexOf("!"));
		else
			place = token;
		
		if(token != null){
			if(place.equals(BoardgamePlace.PLACEID))
			{
				eventBus.fireEvent(new PlaceChangedEvent(new BoardgamePlace(token)));
			}
			if(place.equals(GameTypePlace.PLACEID))
			{
				eventBus.fireEvent(new PlaceChangedEvent(new GameTypePlace(token)));
			}
			if(place.equals(GameSessionPlace.PLACEID))
			{
				eventBus.fireEvent(new PlaceChangedEvent(new GameSessionPlace(token)));
			}
			if(place.startsWith("account"))
			{
				
				//game room selection
			}
		}
	}

}
